package cn.liyao.im.util;

import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.IdUtil;
import cn.hutool.json.JSONUtil;
import cn.liyao.web.constant.ConversationType;
import cn.liyao.web.constant.ReadStatus;
import cn.liyao.web.model.*;
import cn.liyao.web.repository.ConversationRepository;
import cn.liyao.web.repository.GroupMemberRepository;
import cn.liyao.web.repository.UserMessageRepository;
import cn.liyao.web.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import server.protocal.Protocal;

import java.util.List;
import java.util.Optional;

@Service
public class ConversationUtil {

    @Autowired
    private ConversationRepository conversationRepository;


    @Autowired
    private UserRepository userRepository;


    @Autowired
    private UserMessageRepository userMessageRepository;


    @Autowired
    private GroupMemberRepository groupMemberRepository;




    // 创建消息状态表和主消息进行关联
    // //TODO 之后得改成异步的 不然会卡顿
    public void createMessageStatus(Messages messages){
        // 私聊消息
        String messageId =  messages.getFp();
        // 发送人
        String from =  messages.getFrom();
        // 接受人
        String to  =messages.getTo();

        if(messages.getTo().indexOf("group_") == -1){
            Snowflake snowflake =  IdUtil.getSnowflake();
            UserMessage fromMessage = new UserMessage();
            fromMessage.setId(snowflake.nextIdStr());
            fromMessage.setDeletedStatus(0);
            fromMessage.setFp(messageId);
            fromMessage.setReadStatus(ReadStatus.UNREAD);
            fromMessage.setUserId(from);
            fromMessage.setTargetId(to);

            userMessageRepository.save(fromMessage);

            UserMessage toMessage = new UserMessage();
            toMessage.setId(snowflake.nextIdStr());
            toMessage.setDeletedStatus(0);
            toMessage.setFp(messageId);
            toMessage.setReadStatus(ReadStatus.UNREAD);
            toMessage.setUserId(to);
            toMessage.setTargetId(from);

            userMessageRepository.save(toMessage);
        }else{

            Snowflake snowflake =  IdUtil.getSnowflake();
            // 所有的群用户
            List<GroupMember> groupMembers =   groupMemberRepository.findAllByGroupIdAndUserState(messages.getTo(),0);
            for(GroupMember member : groupMembers){
                UserMessage userMessage = new UserMessage();
                userMessage.setId(snowflake.nextIdStr());
                userMessage.setDeletedStatus(0);
                userMessage.setFp(messageId);
                userMessage.setReadStatus(member.getUserId().equals(to) ? ReadStatus.READ : ReadStatus.UNREAD);
                userMessage.setUserId(member.getUserId());
                userMessage.setTargetId(messages.getTo());
                userMessageRepository.save(userMessage);
            }
        }




    }



    public Conversation createGroupConversation(String targetId, String userId, Protocal p){

        p.setFrom(p.getFrom().equals("0")? targetId : p.getFrom());
        Conversation conversation  = conversationRepository.findOneByUserIdAndTargetId(userId,targetId);
        if(conversation == null){
            Optional<User> user = userRepository.findById(userId);
            conversation = new Conversation();
            conversation.setId(IdUtil.getSnowflakeNextIdStr());
            conversation.setLastMessage("");
            conversation.setTargetId(targetId);
            conversation.setUserId(userId);
            conversation.setType(ConversationType.Group.getValue());
            conversation.setUnreadCount(p.getFrom().equals(userId) ? 0 :1 );
            conversation.setTop(false);
            conversation.setDisturb(false);
            conversation.setUserName("");
            conversation.setPortrait("");
            conversation.setTimestamp(System.currentTimeMillis());
            if(user.isPresent()){
                conversation.setUserName(user.get().getNickName());
                conversation.setPortrait(user.get().getUserPortrait());
            }
            conversationRepository.save(conversation);
        }else{

            if(!conversation.getDisturb()){
                if(!p.getFrom().equals(userId)){
                    conversation.setUnreadCount(conversation.getUnreadCount() + 1);
                }else{
                    conversation.setUnreadCount(0);
                }
            }else{
                conversation.setUnreadCount(0);
            }


            conversation.setTimestamp(System.currentTimeMillis());
            conversation = conversationRepository.save(conversation);
        }

        return conversation;
    }


    public   void createOtherPartyConversation(Messages messages){
        Conversation conversation  = conversationRepository.findOneByUserIdAndTargetId(messages.getTo(),messages.getFrom());
        if(conversation == null){
            Optional<User> user = userRepository.findById(messages.getFrom());
            conversation = new Conversation();
            conversation.setId(IdUtil.getSnowflakeNextIdStr());
            conversation.setLastMessage(JSONUtil.toJsonStr(messages));
            conversation.setTargetId(messages.getFrom());
            conversation.setUserId(messages.getTo());
            conversation.setType(ConversationType.Single.getValue());
            conversation.setUnreadCount(1);
            conversation.setTop(false);
            conversation.setDisturb(false);
            conversation.setUserName("");
            conversation.setPortrait("");
            conversation.setTimestamp(System.currentTimeMillis());
            if(user.isPresent()){
                conversation.setUserName(user.get().getNickName());
                conversation.setPortrait(user.get().getUserPortrait());
            }
            conversationRepository.save(conversation);
        }else{


            Conversation opposite  = conversationRepository.findOneByUserIdAndTargetId(messages.getFrom(),messages.getTo());

//            Boolean disturb =  conversation.getDisturb();
            conversation.setLastMessage(JSONUtil.toJsonStr(messages));

            if(opposite.getDisturb()){
                conversation.setUnreadCount(0);
            }else{
                conversation.setUnreadCount(conversation.getUnreadCount() + 1);
            }

            conversation.setTimestamp(System.currentTimeMillis());
            conversationRepository.save(conversation);
        }
    }


    public  void createSelfConversation(Messages messages){
        Conversation conversation  = conversationRepository.findOneByUserIdAndTargetId(messages.getFrom(), messages.getTo());
        if(conversation == null){
            Optional<User> user = userRepository.findById(messages.getTo());
            conversation = new Conversation();
            conversation.setId(IdUtil.getSnowflakeNextIdStr());
            conversation.setLastMessage(JSONUtil.toJsonStr(messages));
            conversation.setTargetId(messages.getTo());
            conversation.setUserId(messages.getFrom());
            conversation.setType(ConversationType.Single.getValue());
            conversation.setUnreadCount(0);
            conversation.setTop(false);
            conversation.setDisturb(false);
            conversation.setUserName("");
            conversation.setPortrait("");
            conversation.setTimestamp(System.currentTimeMillis());
            if(user.isPresent()){
                conversation.setUserName(user.get().getNickName());
                conversation.setPortrait(user.get().getUserPortrait());
            }
            conversationRepository.save(conversation);
        }else{
            conversation.setLastMessage(JSONUtil.toJsonStr(messages));
            conversation.setUnreadCount(0);
            conversation.setTimestamp(System.currentTimeMillis());
            conversationRepository.save(conversation);
        }
    }
}
